<?php

namespace auth;

use think\Db;

class AuthMenu extends Auth
{
    /**
     * 对菜单无限级分类
     * @param $cate
     * @param string $name
     * @param int $pid
     * @return array
     */
    public function unlimitedForLayer($cate, $name = 'child', $pid = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v[$name] = $this->unlimitedForLayer($cate, $name, $v['id']);
                $arr[] = $v;
            }
        }
        return $arr;
    }

    /**
     * 从数据库读取菜单
     * @return array
     */
    public function getAllMenu()
    {
        $ruleList = Db::name('auth_rule')
            ->field('id,pid,name,title,status,icon')
            ->where('isMenu', 1)
            ->order('id asc')
            ->select();     //读取用作为菜单显示的
        foreach ($ruleList as $k => &$v) {

            $v['name'] = '/'  . $v['name'];

        }
        $menu = $this->unlimitedForLayer($ruleList);
        return $menu;
    }

    /**
     * 获取菜单
     * @param $auth_id
     * @return array
     */
    public function getMenuList($auth_id)
    {
        //根据角色权限过滤菜单
        $menuList = $this->getAllMenu();   //获取所有菜单
        if ($auth_id != 1) {   //超级管理员加载所有菜单
            $auth = new Auth();
            $authList = $auth->getAuthList($auth_id, 1); //获取用户需要验证的所有有效规则列表
            //p($authList);
            $map['name'] = ['in', $authList];
            $roleRight = db('auth_rule')->where($map)->column('id');
            //p($roleRight);
            foreach ($menuList as $k => $v) {
                if (!in_array($v['id'], $roleRight)) {    //判断数组是否在菜单表里面
                    unset($menuList[$k]);//过滤菜单
                }
                foreach ($v['child'] as $kk => $vv) {
                    if (!in_array($vv['id'], $roleRight)) {    //判断数组是否在菜单表里面
                        unset($menuList[$k]['child'][$kk]);//过滤菜单
                    }
                }
            }

        }
        return $menuList;
    }
}